package com.hyg.lib_music.network;

import android.content.Context;
import android.os.Environment;
import android.util.Log;

import com.google.gson.Gson;
import com.hyg.lib_common.Base.BaseApplication;
import com.hyg.lib_common.DataModel.Music.Music;
import com.hyg.lib_common.DataModel.Music.response.BaseResponse;
import com.hyg.lib_common.DataModel.Music.response.CateListResponse;
import com.hyg.lib_common.DataModel.Music.response.CategoryListResponse;
import com.hyg.lib_common.DataModel.Music.response.DocListResponse;
import com.hyg.lib_common.DataModel.Music.response.FavoriteListReponse;
import com.hyg.lib_common.DataModel.Music.response.MusicListResponse;
import com.hyg.lib_common.DataModel.Music.response.RecommendResponse;
import com.hyg.lib_common.DataUtil.UserSPUtils;
import com.hyg.lib_common.constant.UrlUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;


public class NetManager {

    private static final NetManager manager = new NetManager();
    private static Context mContext;

    public static NetManager sharedManager(Context context) {
        if (context != null) {
            NetManager.mContext = context;
        }
        return manager;
    }

    public static NetManager sharedManager() {
        return manager;
    }


    /**
     * 通用添加header
     *
     * @param url  地址
     * @param body form内容
     * @return Request
     */
    public Request buildRequest(String url, RequestBody body) {

        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        return request;
    }


    /**
     * 获取token
     *
     * @return void
     */
    public String getToken() {
        String token = UserSPUtils.getToken(BaseApplication.getAppContext());
        return token;
    }

    /**
     * 推荐列表
     *
     * @return RecommendResponse
     */
    public RecommendResponse recommendRequest() {
        OkHttpClient client = new OkHttpClient();

        Request.Builder reqBuild = new Request.Builder();
        HttpUrl.Builder urlBuilder = HttpUrl.parse(UrlUtils.RECOMMEND)
                .newBuilder();
        urlBuilder.addQueryParameter("token", this.getToken());

        Log.i("lgb", "recommendRequest: "+this.getToken());

        reqBuild.url(urlBuilder.build());
        Request request = reqBuild.build();

        try {
            Response httpResponse = client.newCall(request).execute();

            if (httpResponse.isSuccessful()) {
                Gson gson = new Gson();
                String jsonstr = httpResponse.body().string();
                RecommendResponse response = gson.fromJson(jsonstr, RecommendResponse.class);

                return response;
            } else {
//                ld.loadFailed();
                throw new IOException("Unexpected code " + httpResponse);
            }
        } catch (Exception e) {
//            ld.loadFailed();
            return null;
        }
    }

    /**
     * 音乐列表
     *
     * @return MusicListResponse
     */
    public MusicListResponse musicListRequest(int categoryId) {
        OkHttpClient client = new OkHttpClient();

        Request.Builder reqBuild = new Request.Builder();
        HttpUrl.Builder urlBuilder = HttpUrl.parse(UrlUtils.MUSIC_LIST)
                .newBuilder();
        urlBuilder.addQueryParameter("categoryId", categoryId + "");
//        urlBuilder.addQueryParameter("token", this.token);
        reqBuild.url(urlBuilder.build());
        Request request = reqBuild.build();

        try {
            Response httpResponse = client.newCall(request).execute();

            if (httpResponse.isSuccessful()) {
                Gson gson = new Gson();
                String jsonstr = httpResponse.body().string();
                MusicListResponse response = gson.fromJson(jsonstr, MusicListResponse.class);

                return response;
            } else {
//                ld.loadFailed();
                throw new IOException("Unexpected code " + httpResponse);
            }
        } catch (Exception e) {
//            ld.loadFailed();
            return null;
        }
    }

    /**
     * 分类列表
     *
     * @return CategoryListResponse
     */
    public CategoryListResponse categoryListRequest(int categoryId) {
        OkHttpClient client = new OkHttpClient();

        Request.Builder reqBuild = new Request.Builder();
        HttpUrl.Builder urlBuilder = HttpUrl.parse(UrlUtils.CATEGORY_LIST)
                .newBuilder();
        urlBuilder.addQueryParameter("categoryId", categoryId + "");
//        urlBuilder.addQueryParameter("token", this.token);
        reqBuild.url(urlBuilder.build());
        Request request = reqBuild.build();

        try {
            Response httpResponse = client.newCall(request).execute();

            if (httpResponse.isSuccessful()) {
                Gson gson = new Gson();
                String jsonstr = httpResponse.body().string();
                CategoryListResponse response = gson.fromJson(jsonstr, CategoryListResponse.class);

                return response;
            } else {
//                ld.loadFailed();
                throw new IOException("Unexpected code " + httpResponse);
            }
        } catch (Exception e) {
//            ld.loadFailed();
            return null;
        }
    }

    /**
     * 知识分类列表
     *
     * @return BaseResponse
     */
    public CateListResponse cateListRequest(int cateId) {
        OkHttpClient client = new OkHttpClient();

        Request.Builder reqBuild = new Request.Builder();
        HttpUrl.Builder urlBuilder = HttpUrl.parse(UrlUtils.CATE_LIST)
                .newBuilder();
        urlBuilder.addQueryParameter("categoryId", cateId + "");
//        urlBuilder.addQueryParameter("token", this.token);
        reqBuild.url(urlBuilder.build());
        Request request = reqBuild.build();

        try {
            Response httpResponse = client.newCall(request).execute();

            if (httpResponse.isSuccessful()) {
                Gson gson = new Gson();
                String jsonstr = httpResponse.body().string();
                CateListResponse response = gson.fromJson(jsonstr, CateListResponse.class);

                return response;
            } else {
//                ld.loadFailed();
                throw new IOException("Unexpected code " + httpResponse);
            }
        } catch (Exception e) {
//            ld.loadFailed();
            return null;
        }
    }

    /**
     * 添加到我喜欢
     *
     * @return BaseResponse
     */
    public BaseResponse addFavoriteRequest(int musicId) {
        OkHttpClient client = new OkHttpClient();

        FormBody body = new FormBody.Builder()
                .build();
        Request request = buildRequest(UrlUtils.ADD_FAVORITE + "?token=" + this.getToken() + "&musicId=" + musicId, body);

        try {
            Response httpResponse = client.newCall(request).execute();

            if (httpResponse.isSuccessful()) {
                Gson gson = new Gson();
                String jsonstr = httpResponse.body().string();
                BaseResponse response = gson.fromJson(jsonstr, BaseResponse.class);

                return response;
            } else {
//                ld.loadFailed();
                throw new IOException("Unexpected code " + httpResponse);
            }
        } catch (Exception e) {
//            ld.loadFailed();
            return null;
        }
    }

    /**
     * 从我喜欢删除
     *
     * @return BaseResponse
     */
    public BaseResponse removeFavoriteRequest(int musicId) {
        OkHttpClient client = new OkHttpClient();

        FormBody body = new FormBody.Builder()
                .build();
        Request request = buildRequest(UrlUtils.REMOVE_FAVORITE + "?token=" + this.getToken() + "&musicId=" + musicId, body);

        try {
            Response httpResponse = client.newCall(request).execute();

            if (httpResponse.isSuccessful()) {
                Gson gson = new Gson();
                String jsonstr = httpResponse.body().string();
                BaseResponse response = gson.fromJson(jsonstr, BaseResponse.class);

                return response;
            } else {
//                ld.loadFailed();
                throw new IOException("Unexpected code " + httpResponse);
            }
        } catch (Exception e) {
//            ld.loadFailed();
            return null;
        }
    }

    /**
     * 我喜欢音乐列表
     *
     * @return MusicListResponse
     */
    public FavoriteListReponse musicFavListRequest() {
        OkHttpClient client = new OkHttpClient();

        FormBody body = new FormBody.Builder()
                .build();
        Request request = buildRequest(UrlUtils.LIST_FAVORITE + "?token=" + this.getToken(), body);

        try {
            Response httpResponse = client.newCall(request).execute();

            if (httpResponse.isSuccessful()) {
                Gson gson = new Gson();
                String jsonstr = httpResponse.body().string();
                FavoriteListReponse response = gson.fromJson(jsonstr, FavoriteListReponse.class);

                return response;
            } else {
//                ld.loadFailed();
                throw new IOException("Unexpected code " + httpResponse);
            }
        } catch (Exception e) {
//            ld.loadFailed();
            return null;
        }
    }

    /**
     * 文章列表
     *
     * @return DocListResponse
     */
    public DocListResponse docListRequest(int cateId) {
        OkHttpClient client = new OkHttpClient();

        Request.Builder reqBuild = new Request.Builder();
        HttpUrl.Builder urlBuilder = HttpUrl.parse(UrlUtils.DOC_LIST)
                .newBuilder();
        urlBuilder.addQueryParameter("categoryId", cateId + "");
//        urlBuilder.addQueryParameter("token", this.token);
        reqBuild.url(urlBuilder.build());
        Request request = reqBuild.build();

        try {
            Response httpResponse = client.newCall(request).execute();

            if (httpResponse.isSuccessful()) {
                Gson gson = new Gson();
                String jsonstr = httpResponse.body().string();
                DocListResponse response = gson.fromJson(jsonstr, DocListResponse.class);

                return response;
            } else {
//                ld.loadFailed();
                throw new IOException("Unexpected code " + httpResponse);
            }
        } catch (Exception e) {
//            ld.loadFailed();
            return null;
        }
    }


    /**
     * 音乐下载
     *
     * @return void
     */
    public BaseResponse musicDownloadRequest(Music music) {
        OkHttpClient client = new OkHttpClient();

        FormBody formBody = new FormBody.Builder()
                .build();
        Request request = buildRequest(UrlUtils.DOWNLOAD + "?token=" + this.getToken() + "&musicId=" + music.id, formBody);

        try {
            Response httpResponse = client.newCall(request).execute();

//                if (httpResponse.isSuccessful())
            {

                //获取下载的内容输入流
                ResponseBody body = httpResponse.body();
                InputStream inputStream = body.byteStream();
                final long lengh = body.contentLength();
                Log.d("NetManager", "文件大小 " + lengh);
                System.out.println("文件大小" + lengh);
                // 文件保存到本地
                File file1 = Environment.getExternalStorageDirectory();
                File file = new File(file1, music.musicName);
                FileOutputStream outputStream = new FileOutputStream(file);
                int lien = 0;
                int losing = 0;
                byte[] bytes = new byte[1024];
                while ((lien = inputStream.read(bytes)) != -1) {
                    outputStream.write(bytes, 0, lien);

                    losing += lien;
                    final float i = losing * 1.0f / lengh;
                    Log.d("NetManager", "下载进度 " + i);
                }
                outputStream.flush();
                inputStream.close();
                outputStream.close();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return new BaseResponse();
    }

}
